<?php

namespace app\exception;

use app\enum\StatusCode;
use app\helper\Result;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\Response;
use Throwable;

class ExceptionHandle extends Handle
{
    public function render($request, Throwable $e): Response
    {
        // 参数验证错误
        if ($e instanceof ValidateException) {
            return Result::fail(StatusCode::PARAM_ERROR->value, $e->getError());
        }

        if ($e instanceof BusinessException) {
            return Result::fail($e->getCode(), $e->getMessage());
        }

        // 请求异常
        if ($e instanceof HttpException && $request->isAjax()) {
            return response($e->getMessage(), $e->getStatusCode());
        }

        // 其他错误交给系统处理
        return parent::render($request, $e);
    }
}
